package com.ruoyi.college.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.service.impl.BaseServiceImpl;
import com.ruoyi.college.domain.ExperimentProject;
import com.ruoyi.college.mapper.ExperimentProjectMapper;
import com.ruoyi.college.service.IExperimentProjectService;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 实验项目Service实现类
 * @author ruoyi
 * @date 2024-05-XX
 */
@Service
public class ExperimentProjectServiceImpl extends BaseServiceImpl<ExperimentProject,ExperimentProjectMapper> implements IExperimentProjectService {
    /** 上传文件保存路径（从配置文件读取） */
    @Value("${ruoyi.upload.path}")
    private String uploadPath;

    @Autowired
    private ExperimentProjectMapper experimentProjectMapper;

    public ExperimentProjectServiceImpl(ExperimentProjectMapper baseMapper) {
        super(baseMapper); // 关键：将具体 Mapper 传递给父类
    }

    /**
     * 按课程安排ID查询实验项目列表
     */
    @Override
    public List<ExperimentProject> getProjectListByArrangementId(Integer arrangementId) {
        return experimentProjectMapper.selectProjectListByArrangementId(arrangementId);
    }

    /**
     * 添加实验项目（含附件上传）
     */
    @Override
    public AjaxResult addExperimentProject(ExperimentProject project, MultipartFile[] files) {
        try {
            // 1. 处理附件上传（若有）
            if (files != null && files.length > 0) {
                List<String> attachmentPaths = new ArrayList<>();
                for (MultipartFile file : files) {
                    // 调用若依工具类上传文件，返回相对路径（如：/upload/2024/08/xxx.pdf）
                    String filePath = FileUploadUtils.upload(RuoYiConfig.getExperimentAttachmentUploadPath(), file);
                    attachmentPaths.add(filePath);
                }
                // 多个附件用逗号分隔存入数据库
                project.setAttachment(String.join(",", attachmentPaths));
            }
            project.setCreateTime(new Date());

            // 2. 保存实验项目信息
            experimentProjectMapper.insert(project);
            return AjaxResult.success("实验项目添加成功");
        } catch (Exception e) {
            //log.error("添加实验项目失败：", e);
            return AjaxResult.error("添加失败，请重试");
        }
    }

    /**
     * 修改实验项目（含附件更新）
     */
    @Override
    public AjaxResult updateExperimentProject(ExperimentProject project, MultipartFile[] files) {
        try {
            // 1. 若有新附件，先上传并拼接路径
            if (files != null && files.length > 0) {
                List<String> attachmentPaths = new ArrayList<>();
                // 保留原附件（如需覆盖可先删除原文件）
                if (project.getAttachment() != null && !project.getAttachment().isEmpty()) {
                    String[] oldPaths = project.getAttachment().split(",");
                    for (String oldPath : oldPaths) {
                        attachmentPaths.add(oldPath);
                    }
                }
                // 上传新附件
                for (MultipartFile file : files) {
                    String newPath = FileUploadUtils.upload(uploadPath, file);
                    attachmentPaths.add(newPath);
                }
                project.setAttachment(String.join(",", attachmentPaths));
            }

            // 2. 更新实验项目信息
            experimentProjectMapper.updateById(project);
            return AjaxResult.success("实验项目修改成功");
        } catch (Exception e) {
            //log.error("修改实验项目失败：", e);
            return AjaxResult.error("修改失败，请重试");
        }
    }

    /**
     * 批量删除实验项目（含附件物理删除）
     */
    @Override
    public AjaxResult deleteProjectByIds(Long[] projectIds) {
        try {
            // 1. 先查询所有要删除的项目，获取附件路径
            List<Long> list = Arrays.asList(projectIds);
            List<ExperimentProject> projects = experimentProjectMapper.selectBatchIds(list);
            for (ExperimentProject project : projects) {
                // 物理删除附件文件
                if (project.getAttachment() != null && !project.getAttachment().isEmpty()) {
                    String[] paths = project.getAttachment().split(",");
                    for (String path : paths) {
                        //File file = new File(uploadPath + path.replace("/upload/", ""));
                        String fileName = uploadPath + path.replace("/upload/", "");
                        FileUtils.deleteFile(fileName);
                    }
                }
            }

            // 2. 批量删除数据库记录
            experimentProjectMapper.deleteProjectByIds(projectIds);
            return AjaxResult.success("实验项目删除成功");
        } catch (Exception e) {
            //log.error("删除实验项目失败：", e);
            return AjaxResult.error("删除失败，请重试");
        }
    }

    @Override
    public List<ExperimentProject> getProjectsByArrangementId(Integer arrangementId) {
        return experimentProjectMapper.selectProjectListByArrangementId(arrangementId);
    }

    @Override
    public ExperimentProject getProjectByProjectId(Long projectId) {
        return experimentProjectMapper.selectById(projectId);
    }
}